articles

home / developersection / articles / simple image to cartoon images

simple image to cartoon images

simple image to cartoon images

ICSM Computer 1463 11-Feb-2025

In C#, you can convert an image into a cartoon-style image using image processing libraries like OpenCV (via Emgu CV) or Accord.NET. The basic idea is to apply edge detection and then blend it with a simplified color version of the image.

 

Steps to Convert an Image to a Cartoon in C#

  1. Load the Image
  2. Apply Bilateral Filter (to smooth colors while preserving edges)
  3. Detect Edges (using Canny or Laplacian edge detection)
  4. Convert to Grayscale and Apply Threshold
  5. Combine the Edge Mask with the Smoothened Image

 

Code Using Emgu CV (OpenCV for .NET)

using System;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;

class Program
{
    static void Main()
    {
        string inputPath = "input.jpg";  // Replace with your image path
        string outputPath = "cartoon.jpg";

        Mat src = CvInvoke.Imread(inputPath, ImreadModes.Color);

        // Apply Bilateral Filter for smoothing
        Mat smooth = new Mat();
        CvInvoke.BilateralFilter(src, smooth, 9, 75, 75);

        // Convert to Grayscale
        Mat gray = new Mat();
        CvInvoke.CvtColor(src, gray, ColorConversion.Bgr2Gray);

        // Apply Median Blur to reduce noise
        CvInvoke.MedianBlur(gray, gray, 7);

        // Detect edges using Adaptive Threshold
        Mat edges = new Mat();
        CvInvoke.AdaptiveThreshold(gray, edges, 255, AdaptiveThresholdType.MeanC, ThresholdType.Binary, 9, 2);

        // Convert edges to color
        Mat colorEdges = new Mat();
        CvInvoke.CvtColor(edges, colorEdges, ColorConversion.Gray2Bgr);

        // Combine edges with the smoothened image using bitwise_and
        Mat cartoon = new Mat();
        CvInvoke.BitwiseAnd(smooth, colorEdges, cartoon);

        // Save the cartoonized image
        CvInvoke.Imwrite(outputPath, cartoon);

        Console.WriteLine("Cartoon image saved at " + outputPath);
    }
}

 

Installation Requirements

  1. Install Emgu.CV from NuGet:
Install-Package Emgu.CV Install-Package Emgu.CV.runtime.windows 

2. Ensure OpenCV dependencies are available in your project.

 

The result is a cartoonized version of your input image with bold outlines and smooth colors.

Would you like help integrating this into a GUI application (like Windows Forms or WPF)? 


Updated 12-Feb-2025
ICSM Computer

IT-Hardware & Networking

Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.

Leave Comment

Comments

Liked By